// 加载课程数据
async function loadCourseData() {
    try {
        const response = await fetch('../data/courses.json');
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error loading course data:', error);
        return null;
    }
}

// 生成随机颜色
function getRandomColor() {
    const colors = [
        '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', 
        '#FFEEAD', '#D4A5A5', '#9B59B6', '#3498DB',
        '#E74C3C', '#2ECC71', '#F1C40F', '#1ABC9C'
    ];
    return colors[Math.floor(Math.random() * colors.length)];
}

// 复制文本到剪贴板
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        // 可以添加复制成功的提示
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.textContent = '复制成功！';
        document.body.appendChild(toast);
        
        // 2秒后移除提示
        setTimeout(() => {
            toast.remove();
        }, 2000);
    }).catch(err => {
        console.error('复制失败:', err);
    });
}

// 渲染课程卡片
function renderCourseCard(course) {
    const backgroundColor = getRandomColor();
    const placeholder = course.img 
        ? `<img src="${course.img}" alt="${course.title}" class="course-image">`
        : `<div class="color-placeholder" style="background-color: ${backgroundColor}">${course.title}</div>`;

    return `
        <div class="course-card">
            <a href="${course.url}" target="_blank" class="course-link">
                ${placeholder}
                <div class="course-info">
                    <div class="title-container">
                        <h3 class="course-title">${course.title}</h3>
                        <button class="copy-btn" onclick="event.preventDefault(); copyToClipboard('${course.title}')">
                            <span class="copy-icon">📋</span>
                        </button>
                    </div>
                    <p class="course-desc">${course.description}</p>
                    <div class="course-meta">
                        <span>${course.category}</span>
                        <span>${course.studentsCount}人学习</span>
                    </div>
                </div>
            </a>
        </div>
    `;
}

// 渲染课程列表
function renderCourses(courses) {
    const courseContainer = document.getElementById('courseContainer');
    if (!courseContainer) return;

    const coursesHTML = courses.map(renderCourseCard).join('');
    courseContainer.innerHTML = coursesHTML;
}

// 渲染分类列表
function renderCategories(categories) {
    const categoryList = document.getElementById('categoryList');
    if (!categoryList) return;

    const categoriesHTML = categories.map(category => `
        <li><a href="#" data-category="${category.id}">${category.name}</a></li>
    `).join('');
    
    categoryList.innerHTML = categoriesHTML;
}

// 渲染导航分类
function renderNavCategories(categories) {
    const navCategories = document.getElementById('navCategories');
    if (!navCategories) return;

    const categoriesHTML = categories.map(category => `
        <li><a href="#" data-category="${category.id}">${category.name}</a></li>
    `).join('');
    
    navCategories.innerHTML = categoriesHTML;
}

// 渲染分类过滤器
function renderFilterCategories(categories) {
    const filterContainer = document.getElementById('filterCategories');
    if (!filterContainer) return;

    const allCategories = [
        { id: 'ALL', name: '全部' },
        ...categories
    ];

    const categoriesHTML = allCategories.map((category, index) => `
        <a href="#" class="${index === 0 ? 'active' : ''}" data-category="${category.id}">${category.name}</a>
    `).join('');
    
    filterContainer.innerHTML = categoriesHTML;
}

// 获取所有课程
function getAllCourses(coursesData) {
    const allCourses = [];
    coursesData.forEach(categoryObj => {
        const category = Object.keys(categoryObj)[0];
        categoryObj[category].forEach(course => {
            allCourses.push(course);
        });
    });
    return allCourses;
}

// 获取特定分类的课程
function getCoursesByCategory(coursesData, category) {
    const categoryObj = coursesData.find(obj => obj[category]);
    return categoryObj ? categoryObj[category] : [];
}

// 初始化页面
async function initializePage() {
    const data = await loadCourseData();
    if (!data) return;

    renderCategories(data.categories);
    renderNavCategories(data.categories);
    renderFilterCategories(data.categories);
    renderCourses(getAllCourses(data.courses));

    // 添加导航点击事件监听器
    document.getElementById('navCategories').addEventListener('click', (e) => {
        if (e.target.tagName === 'A') {
            e.preventDefault();
            // 移除所有导航项的active类
            document.querySelectorAll('.nav a').forEach(a => a.classList.remove('active'));
            e.target.classList.add('active');
            
            const category = e.target.dataset.category;
            const filteredCourses = category === 'home' 
                ? getAllCourses(data.courses)
                : getCoursesByCategory(data.courses, category);
            
            renderCourses(filteredCourses);
        }
    });

    // 首页链接点击事件
    document.querySelector('.nav a.active').addEventListener('click', (e) => {
        e.preventDefault();
        document.querySelectorAll('.nav a').forEach(a => a.classList.remove('active'));
        e.target.classList.add('active');
        renderCourses(getAllCourses(data.courses));
    });

    // 添加分类筛选事件监听器
    document.getElementById('filterCategories').addEventListener('click', (e) => {
        if (e.target.tagName === 'A') {
            e.preventDefault();
            document.querySelectorAll('#filterCategories a').forEach(a => a.classList.remove('active'));
            e.target.classList.add('active');
            
            const category = e.target.dataset.category;
            const filteredCourses = category === 'ALL' 
                ? getAllCourses(data.courses)
                : getCoursesByCategory(data.courses, category);
            
            renderCourses(filteredCourses);
        }
    });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initializePage);
